type Methods = "GET" | "POST" | "PUT" | "DELETE";
interface AjaxOptions {
  // 请求方式 默认GET请求
  method: Methods;
  // 请求地址
  url: string;
  // 请求参数
  data?: any;
  config?: {
    // 配置请求头
    headers?: { [key: string]: string };
    // 请求参数存放key值 默认query
    dataName?: string;
  };
}
/**
 * 发送HTTP网络请求
 */
function request<T>(options: AjaxOptions): Promise<T> {
  return new Promise((resolve, reject) => {
    let { method = "GET", url, data, config } = options;
    const ajax = new XMLHttpRequest();
    if (method === "GET") {
      url += "?";
      for (const key in data) {
        url += `${key}=${data[key]}&`;
      }
    }
    ajax.open(method, url);
    ajax.setRequestHeader("Content-Type", "application/json");
    if (config && config.headers) {
      for (const key in config.headers) {
        ajax.setRequestHeader(key, config.headers[key]);
      }
    }
    ajax.onreadystatechange = function () {
      if (ajax.readyState === 4 && ajax.status === 200) {
        if (ajax.responseText === "") return;
        resolve(JSON.parse(ajax.response));
      } else if (ajax.status === 404) {
        reject();
      }
    };
    ajax.onerror = function (error: ProgressEvent<EventTarget>) {
      console.log("request error:", error);
      reject(error);
    };
    if (method === "GET") {
      ajax.send();
    } else {
      ajax.send(
        data &&
          JSON.stringify({ [(config && config.dataName) || "query"]: data })
      );
    }
  });
}
type AjaxReuqset = Omit<AjaxOptions, "url" | "method">;

/** 二次封装Ajax请求 */
export default class Ajax {
  static get<T>(url: string, config?: AjaxReuqset): Promise<any> {
    const { data } = config || {};
    return request<T>({
      method: "GET",
      url,
      data: data || {},
    });
  }
  static post<T>(url: string, config?: AjaxReuqset): Promise<any> {
    const { data } = config || {};
    return request<T>({
      method: "POST",
      url,
      data: data || {},
    });
  }
}
